//
// connection.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include "connection.hpp"
#include <vector>
#include <boost/bind.hpp>
#include "request_handler.hpp"

Connection::Connection(boost::asio::io_service& io_service,
                       request_handler& handler)
        : strand_(io_service),
        socket_(io_service),
        request_handler_(handler)
{
}

boost::asio::ip::tcp::socket& Connection::socket()
{
    return socket_;
}

void Connection::start()
{
    std::cout<< "Start a connection" << std::endl ;
    boost::asio::async_read(socket_, boost::asio::buffer(inMsg.data(), Message::HEADER_LEN),
                            strand_.wrap(
                                boost::bind(&Connection::handle_read_header, shared_from_this(),
                                            boost::asio::placeholders::error)));
}

void Connection::write()
{
    LOGCON.infoStream() << outReply ;
    boost::asio::async_write(socket_, boost::asio::buffer(outReply.data(),outReply.size()),
                             boost::bind(&Connection::handle_write, this,
                                         boost::asio::placeholders::error));

}
void Connection::handle_read_header(const boost::system::error_code& e)
{
    if (!e && inMsg.decode_header())
    {
        boost::asio::async_read(socket_, boost::asio::buffer(inMsg.body(), inMsg.body_length()),
                                strand_.wrap(
                                    boost::bind(&Connection::handle_read_body, shared_from_this(),
                                                boost::asio::placeholders::error)));
    }
}
void Connection::handle_read_body(const boost::system::error_code& error)
{
    if (!error)
    {
        request_handler_.handle_request(inMsg, outReply) ;
        write();
        boost::asio::async_read(socket_, boost::asio::buffer(inMsg.data(), Message::HEADER_LEN),
                                strand_.wrap(boost::bind(&Connection::handle_read_header, shared_from_this(),
                                                         boost::asio::placeholders::error)));
    }
}
void Connection::handle_write(const boost::system::error_code& e)
{
    if (!e)
    {
        LOGCON.info ("Has written Message\n");
    }
}
